/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iamk.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author ThanhBình
 */
public class SQLUtil {

    public static String getSequenceValue(Connection cn, String sequenceName)
            throws Exception {
        return getSequenceValue(cn, sequenceName, true);
    }

    public static String getSequenceValue(Connection cn, String sequenceName,
            boolean bAutoCreate) throws Exception {
        // SQL command to sequence value
        String strSQL = "SELECT " + sequenceName + ".NEXTVAL FROM DUAL";

        // Get query data
        try {
            Statement stmt = cn.createStatement();
            ResultSet rs = stmt.executeQuery(strSQL);
            rs.next();
            String strReturn = rs.getString(1);
            rs.close();
            stmt.close();
            return strReturn;
        } catch (Exception ex) {
            System.out.println(strSQL);
            if (ex.getMessage() != null
                    && ex.getMessage().startsWith("ORA-02289")) {
                if (!bAutoCreate) {
                    throw ex;
                } else {
                    Statement stmt = cn.createStatement();
                    stmt.executeUpdate("CREATE SEQUENCE " + sequenceName
                            + " START WITH 50");
                    stmt.close();
                    return "1";
                }
            } else {
                throw ex;
            }
        }
    }
}
